package com.example.demo.config.jwt;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        Map<String, Object> map = new HashMap<>();
        map.put("code", "401");
        map.put("data", "");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        if (token != null && !token.isEmpty()) {
            try {
                Boolean boolen = JWTUtil.verifyToken(token);
                return boolen; // Token 验证通过
            } catch (Exception e) {
                map.put("msg", "无效令牌");
                out.print(new ObjectMapper().writeValueAsString(map));
                out.flush();
            }
        }
        map.put("msg", "令牌缺失");
        out.print(new ObjectMapper().writeValueAsString(map));
        out.flush();
        return false; // Token 缺失
    }

}
